import {
  isNode as h,
  isScalar as $,
  isCollection as A,
  isMap as S,
  isSeq as L,
  isPair as m,
  isAlias as w,
} from './nodes/identity.js';
import { parseAllDocuments as y } from './public-api.js';
import { visit as g } from './visit.js';
const O = {
  BLOCK_FOLDED: '>',
  BLOCK_LITERAL: '|',
  PLAIN: ':',
  QUOTE_DOUBLE: '"',
  QUOTE_SINGLE: "'",
};
function E(s, e) {
  let a = !1;
  return (
    g(s, {
      Value(r, c) {
        if (c.anchor === e) return (a = !0), g.BREAK;
      },
    }),
    a
  );
}
function M(s) {
  const e = y(s),
    a = e.find(i => i.errors.length > 0),
    r = a ? a.errors[0].message : null,
    c = ['+STR'];
  try {
    for (let i = 0; i < e.length; ++i) {
      const t = e[i];
      let l = t.contents;
      Array.isArray(l) && (l = l[0]);
      const [f] = t.range || [0],
        o = t.errors[0];
      if (o && (!o.pos || o.pos[0] < f)) throw new Error();
      let n = '+DOC';
      if (t.directives.docStart) n += ' ---';
      else if (
        t.contents &&
        t.contents.range[2] === t.contents.range[0] &&
        !t.contents.anchor &&
        !t.contents.tag
      )
        continue;
      c.push(n), p(c, t, (o == null ? void 0 : o.pos[0]) ?? -1, l);
      let u = '-DOC';
      t.directives.docEnd && (u += ' ...'), c.push(u);
    }
  } catch (i) {
    return { events: c, error: r ?? i };
  }
  return c.push('-STR'), { events: c, error: r };
}
function p(s, e, a, r) {
  if (!r) {
    s.push('=VAL :');
    return;
  }
  if (a !== -1 && h(r) && r.range[0] >= a) throw new Error();
  let c = '',
    i = $(r) || A(r) ? r.anchor : void 0;
  if (i) {
    if (/\d$/.test(i)) {
      const t = i.replace(/\d$/, '');
      E(e, t) && (i = t);
    }
    c = ` &${i}`;
  }
  if ((h(r) && r.tag && (c += ` <${r.tag}>`), S(r))) {
    const t = r.flow ? '+MAP {}' : '+MAP';
    s.push(`${t}${c}`),
      r.items.forEach(({ key: l, value: f }) => {
        p(s, e, a, l), p(s, e, a, f);
      }),
      s.push('-MAP');
  } else if (L(r)) {
    const t = r.flow ? '+SEQ []' : '+SEQ';
    s.push(`${t}${c}`),
      r.items.forEach(l => {
        p(s, e, a, l);
      }),
      s.push('-SEQ');
  } else if (m(r))
    s.push(`+MAP${c}`), p(s, e, a, r.key), p(s, e, a, r.value), s.push('-MAP');
  else if (w(r)) {
    let t = r.source;
    if (t && /\d$/.test(t)) {
      const l = t.replace(/\d$/, '');
      E(e, l) && (t = l);
    }
    s.push(`=ALI${c} *${t}`);
  } else {
    const t = O[String(r.type)];
    if (!t) throw new Error(`Unexpected node type ${r.type}`);
    const l = r.source
      .replace(/\\/g, '\\\\')
      .replace(/\0/g, '\\0')
      .replace(/\x07/g, '\\a')
      .replace(/\x08/g, '\\b')
      .replace(/\t/g, '\\t')
      .replace(/\n/g, '\\n')
      .replace(/\v/g, '\\v')
      .replace(/\f/g, '\\f')
      .replace(/\r/g, '\\r')
      .replace(/\x1b/g, '\\e');
    s.push(`=VAL${c} ${t}${l}`);
  }
}
export { M as testEvents };
